package com.example.weatherreport;

import static com.example.weatherreport.CityWeatherFragment.MSG;

import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.example.weatherreport.R;
import com.example.weatherreport.bean.WeatherBean;
import com.google.gson.Gson;
import com.squareup.picasso.OkHttpDownloader;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class WenxinYanBackend extends AppCompatActivity {

    private EditText questionEditText;
    private Button sendButton;
    private Button weatherButton;
    private TextView answerTextView;
    public static WeatherBean.DataBean.IndexBean index;
    static final OkHttpClient HTTP_CLIENT = new OkHttpClient.Builder()
            .connectTimeout(30, TimeUnit.SECONDS) // 设置连接超时时间为30秒
            .readTimeout(30, TimeUnit.SECONDS) // 设置读取超时时间为30秒
            .build();


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ai_question);

        // 获取布局中的视图引用
        questionEditText = findViewById(R.id.question_edit_text);
        sendButton = findViewById(R.id.send_button);
        weatherButton = findViewById(R.id.weather_button);
        answerTextView = findViewById(R.id.answer_text_view);

        // 设置发送按钮的点击事件监听器
        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String question = questionEditText.getText().toString().trim();
                if (!question.isEmpty()) {
                    getAnswerFromWenxinYan(question);
                }
            }
        });

        weatherButton.setOnClickListener(v -> {
                getAdvice();

        });
    }

    private void getAdvice() {

        @SuppressLint("StaticFieldLeak") AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... params) {
                try {
                    MediaType mediaType = MediaType.parse("application/json");
                    RequestBody body = RequestBody.create(mediaType, "{\"messages\":[{\"role\":\"user\",\"content\":\""+"现在我将给你一份天气相关的情况，请你根据相关情况给出3点不同的生活小建议，开头复述我所给我天气情况，长度请限制在180字左右："+MSG+"\"}]}");
                    Request request = new Request.Builder()
                            .url("https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token=24.f12cb780f8897480802e0a073239b2e4.2592000.1702871081.282335-43204289")
                            .method("POST", body)
                            .addHeader("Content-Type", "application/json")
                            .build();
                    Response response = HTTP_CLIENT.newCall(request).execute();
                    JSONObject json = new JSONObject(response.body().string());
                    return json.getString("result");
                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(String result) {
                super.onPostExecute(result);
                if (result != null) {
                    System.out.println(result);
                    answerTextView.setText(result);
                    // 在这里处理返回的结果
                }
            }
        };

        task.execute();


    }

    private void getAnswerFromWenxinYan(String question) {
        @SuppressLint("StaticFieldLeak") AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... params) {
                try {
                    MediaType mediaType = MediaType.parse("application/json");
                    RequestBody body = RequestBody.create(mediaType, "{\"messages\":[{\"role\":\"user\",\"content\":\""+question+"\"}]}");
                    Request request = new Request.Builder()
                            .url("https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token=24.f12cb780f8897480802e0a073239b2e4.2592000.1702871081.282335-43204289")
                            .method("POST", body)
                            .addHeader("Content-Type", "application/json")
                            .build();
                    Response response = HTTP_CLIENT.newCall(request).execute();
                    JSONObject json = new JSONObject(response.body().string());
                    return json.getString("result");
                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(String result) {
                super.onPostExecute(result);
                if (result != null) {
//                    System.out.println(result);
                    answerTextView.setText(result);
                    // 在这里处理返回的结果
                }
            }
        };

        task.execute();
    }


    private String parseAnswerFromResponse(String response) {
        // 解析文心一言API的响应结果，获取回答
        // 假设返回的JSON中包含一个名为"answer"的字段作为回答内容
        return ""; // 替换为实际解析逻辑
    }

    private void updateAnswer(final String answer) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                answerTextView.setText(answer);
            }
        });
    }

    static class ChatRequest {
        ChatMessage[] messages;
    }

    static class ChatMessage {
        String question;
    }
}
